<template>
  <div class="page-wrap">
    <Table class="table" filter v-bind="tableOpts" defaultExpandAll v-on="tableEvent">
      <template #operator>
        <div class="operator-wrap">
          <modifyOrder
            v-if="authority.includes(200)"
            ref="dialogRef"
            @change="fetchCurrentTable"
          />
          <modifyCAD orderType="old" ref="CADRef" @change="fetchCurrentTable" />
          <modifyAddition ref="additionRef" @change="fetchCurrentTable" />
          <modifyConfirm ref="confirmRef" @change="fetchCurrentTable" />
          <modifyPayment ref="paymentRef" @change="fetchCurrentTable" />
          <modifyOrderArea ref="orderAreaRef" @change="fetchCurrentTable" />
          <PaymentList ref="paymentListRef" @change="fetchCurrentTable" />
          <AdditionList ref="additionListRef" @change="fetchCurrentTable" />
          <ClassifyDetail ref="classifyDetailRef" @change="fetchCurrentTable" />
          <ParseDetail ref="ParseDetailRef" @change="fetchCurrentTable" />
        </div>
      </template>
    </Table>
  </div>
</template>
<script>
import tableMixins from "@/mixins/tableMixins.vue";
import modifyOrder from "./components/modifyOrder.vue";
import modifyCAD from "./components/modifyCAD.vue";
import modifyAddition from "./components/modifyAddition.vue";
import modifyConfirm from "./components/modifyConfirm.vue";
import modifyPayment from "./components/modifyPayment.vue";
import modifyOrderArea from "./components/modifyOrderArea.vue";
import ParseDetail from "./components/ParseDetail.vue";
import PaymentList from "./PaymentList.vue";
import AdditionList from "./AdditionList.vue";
import ClassifyDetail from "./ClassifyDetail.vue";
import { mapState } from "vuex";
import dayjs from "dayjs";
import Decimal from 'decimal.js';
import { exportXlsx } from '@/utils/public.js'

export default {
  name: "OrderManage",
  mixins: [tableMixins],
  components: {
    ParseDetail,
    ClassifyDetail,
    modifyOrderArea,
    modifyAddition,
    modifyConfirm,
    AdditionList,
    modifyPayment,
    modifyOrder,
    modifyCAD,
    PaymentList,
  },
  mounted() {
    const { authority = [] } = this.$quinn.getStorage("userData") || {};
    this.authorityRule = !authority.includes(299);

  },
  data() {
    return {
      authorityRule: false,
      apiName: "orderList",
      form: {
        storeName: {
          tag: "el-input",
          label: "订单名称",
          value: "",
          props: {
            clearable: true,
            placeholder: "请输入订单名称",
          },
        },
        creatorName: {
          tag: "el-input",
          label: "创建人名称",
          value: "",
          props: {
            clearable: true,
            placeholder: "请输入创建人名称",
          },
        },
        areaId: this.formArea(),
        outStatus: {
          tag: "el-select",
          label: "出库状态",
          value: -1,
          items: [
            { label: "全部", value: -1 },
            { label: "待出库", value: 0 },
            { label: "部分出库", value: 1 },
            { label: "全部出库", value: 2 },
          ],
          props: {},
        },
        orderType: {
          tag: "el-select",
          label: "订单类型",
          value: 1,
          items: [
            { label: "新增店铺", value: 1 },
            { label: "老店升级", value: 2 },
          ],
          props: {},
        },
        // delivery: {
        //   tag: "el-date-picker",
        //   label: "发货日期",
        //   value: "",
        //   props: {
        //     clearable: true,
        //     placeholder: "请选择发货日期",
        //     pickerOptions: {
        //       // disabledDate (time) {
        //       // 	return time.getTime() < dayjs().startOf("day").valueOf();
        //       // },
        //     },
        //   },
        // },
        orderBy: {
          tag: "el-select",
          label: "排序规则",
          value: 1,
          items: [
            { label: "默认排序", value: 1 },
            { label: "发货日期", value: 2 },
            { label: "修改时间", value: 3 },
          ],
          props: {},
        },
        startTime: {
          tag: "el-date-picker",
          label: "开始日期",
          value: "",
          props: {
            clearable: true,
            placeholder: "请选择开始日期",
            pickerOptions: {
              // disabledDate (time) {
              // 	return time.getTime() < dayjs().startOf("day").valueOf();
              // },
            },
          },
        },
        endTime: {
          tag: "el-date-picker",
          label: "结束日期",
          value: "",
          props: {
            clearable: true,
            placeholder: "请选择结束日期",
            pickerOptions: {
              // disabledDate (time) {
              // 	return time.getTime() < dayjs().startOf("day").valueOf();
              // },
            },
          },
        },
      },
    };
  },
  computed: {
    authority() {
      const { authority = [] } = this.$quinn.getStorage("userData") || {};
      return authority || [];
    },
  },
  methods: {
    formatQuery(params) {
      if (!params.orderBy) delete params.orderBy;
      try {
        // const d = dayjs(params.delivery);
        const s = dayjs(params.startTime);
        const e = dayjs(params.endTime);
        // if (d.isValid()) params.deliveryDate = d.format("YYYY-MM-DD");
        if (s.isValid()) params.startTime = s.format("YYYY-MM-DD");
        if (e.isValid()) params.endTime = e.format("YYYY-MM-DD");
      } catch (e) {
        console.log(e);
      }
      if (params.outStatus == -1) delete params.outStatus;
      return params;
    },
    handleAction(opts, row) {
      const { storeName: name, id, area } = row;
      let ref = null;
      const map = {
        CAD: "CADRef",
        addition: "additionRef",
        additionList: "additionListRef",
        payment: "paymentRef",
        paymentList: "paymentListRef",
        area: "orderAreaRef",
      };
      if (opts === "edit") return this.showDialog(opts, row);
      else if (opts === 'exportWarehouseOrder') {
        let params = {
          orderId: row.id,
          type: 1
        }
        this.$api.orderGetOfferDirectoryDown(params).then(res => {
          if (res.length == 0) {
            this.$message('暂无报货单数据!');
            return
          }
          // let data = [['名称','编码','数量','单价','小计']];
          let data = [
            ['零食很忙第六代货架价格清单'],
            ['此报价为不含税报价，发货前付清货款，去货架以付款信息为准，货款未及时付清导致货架安装不及时，时间顺延'],
            [`店铺名称:${row.storeName}`, [], [], `制表日期:${dayjs().format('YYYY-MM-DD HH:mm:ss')}`, []],
            ['序号', '名称', '规格', '数量', '单价', '金额']]
          let totalAmount = new Decimal(0);
          res.map((el, idx) => {
            el.idNum = new Decimal(idx).add(1).toNumber();
            data.push([el.idNum, el.directoryName, el.norms, el.directoryCount, el.directoryFee, el.money]);
            totalAmount = Decimal(totalAmount).plus(el.money);
          })
          data.push([[], ['         拆装费：'], [0], [0], [0], [0]])
          data.push([[], ['          运费：'], [0], [0], [4], [0]])
          data.push([[], [], [], [], ['总计：'], [totalAmount]])
          exportXlsx(data, '老店升级-零食很忙', row.storeName)
        })
        // this.$api.orderGetOfferDirectoryDown(params).then(res=>{
        //   if(res.length== 0){
        //     this.$message('暂无CAD数据!');
        //     return
        //   }
        //   let data = [['名称','编码','数量','单价','小计']];
        //   let totalAmount = new Decimal(0);
        //   res.map(el=>{
        //     el.total = Decimal(el.directoryCount).mul(Decimal(el.directoryFee)).toNumber();
        //     data.push([el.directoryName,el.directoryCode,el.directoryCount,el.directoryFee,el.total])
        //     totalAmount = Decimal(totalAmount).plus(el.total)
        //   })
        //   data[data.length + 1] = ['合计:' + totalAmount]
        //   exportXlsx(data,'仓储区',row.storeName)
        // });
      } else if (opts == 'exportShelveOrder') {
        let params = {
          orderId: row.id,
          type: 1
        }
        this.$api.orderGetOfferDirectoryDown(params).then(res => {
          if (res.length == 0) {
            this.$message('暂无CAD数据!');
            return
          }
          let data = [['名称', '编码', '数量', '单价', '小计']];
          let totalAmount = new Decimal(0);
          res.map(el => {
            el.total = Decimal(el.directoryCount).mul(Decimal(el.directoryFee)).toNumber();
            data.push([el.directoryName, el.directoryCode, el.directoryCount, el.directoryFee, el.total])
            totalAmount = Decimal(totalAmount).plus(el.total)
          })
          data[data.length + 1] = ['合计:' + totalAmount]
          exportXlsx(data, '营业区', row.storeName)
        });
      } else if (opts == "costs")
        this.$api["newOrderCosts"]({
          id,
        }).then(({ costs = [] }) => {
          this.$quinn.expTable({
            fileName: `${name}-成本`,
            data: [costs],
            columns: [
              { label: "杂项成本", prop: "additionCost" },
              { label: "产品成本", prop: "materialCost" },
              { label: "安装成本", prop: "installCost" },
              { label: "售后成本", prop: "afterSaleCost" },
              { label: "总成本", prop: "totalCost" },
              { label: "报价单", prop: "saveOrder" },
            ],
          });
        });
      else if (opts == "delete") {
        this.showConfirm(`确认删除【${name}】？`, "orderOrderDelete", { id });
      } else if (opts == "returnInventory") {
        this.showConfirm(`确认回滚【${name}】的全部库存吗？`, "orderCancelRollbackInventory", { orderId: id, areaId: area });
      } else if (opts == "getCadName") {
        this.showConfirm(`确认认领【${name}】的CAD操作吗？`, "orderUpdateOrderCadUserId", { orderId: id });
      } else if (["storageDetail", "goodsDetail", 'goodsOfferDetail', 'storageOffer',].includes(opts)) {
        if (opts == 'storageDetail') row.type = 'storage'
        if (opts == 'goodsDetail') row.type = 'goods'
        if (opts == 'goodsOfferDetail') row.type = 'goodsOfferDetail'
        if (opts == 'storageOffer') row.type = 'storageOffer'
        ref = this.$refs.ParseDetailRef;
        // classifyDetailRef;
      } else if (opts == "confirmOrder") {
        ref = this.$refs.confirmRef;
      } else ref = this.$refs[map[opts]];
      ref && ref.showDialog(opts, row);
    },
  },
};
</script>

<style lang="less" scoped>
:deep(.el-table__expanded-cell) {
  padding: 0;
}

.table /deep/ .el-image {
  //border: 4px solid #15f5d0;
  width: calc(100% + 12px);
  height: calc(100% + 8px);
  border-radius: 3px;
}
</style>
